package com.childenglish.controller;

import com.childenglish.entity.SysClass;
import com.childenglish.entity.SysStudentClass;
import com.childenglish.entity.SysUser;
import com.childenglish.mapper.SysClassMapper;
import com.childenglish.mapper.SysStudentClassMapper;
import com.childenglish.mapper.SysUserMapper;
import com.childenglish.service.PictureBookService;
import com.childenglish.utils.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/learning")
public class LearningController {

    @Autowired
    private PictureBookService pictureBookService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysClassMapper sysClassMapper;

    @Autowired
    private SysStudentClassMapper sysStudentClassMapper;

    @RequiresPermissions("learning:listening:view")
    @GetMapping("/listening")
    public R getListeningMaterials() {
        Map<String, Object> data = new HashMap<>();
        data.put("materials", new String[]{
                "儿童英语儿歌合集",
                "基础单词发音练习",
                "日常对话听力训练"
        });
        data.put("recommended", "儿童英语儿歌合集");
        return R.ok("获取磨耳朵材料成功").data(data);
    }

    /**
     * 获取推荐绘本列表（根据学生的基础和年龄段推荐）
     */
    @RequiresPermissions("learning:reading:view")
    @GetMapping("/reading/books")
    public R getRecommendedBooks() {
        try {
            // 获取当前登录用户
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()) {
                return R.error("用户未登录");
            }

            SysUser currentUser = (SysUser) subject.getPrincipal();
            if (currentUser == null) {
                return R.error("无法获取用户信息");
            }

            // 获取推荐绘本
            List<Map<String, Object>> books = pictureBookService.getRecommendedBooks(currentUser.getId());

            Map<String, Object> data = new HashMap<>();
            data.put("books", books);
            return R.ok("获取推荐绘本成功").data(data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取推荐绘本失败: " + e.getMessage());
        }
    }

    /**
     * 获取绘本详情
     */
    @RequiresPermissions("learning:reading:view")
    @GetMapping("/reading/books/{bookId}")
    public R getBookDetail(@PathVariable Long bookId) {
        try {
            Map<String, Object> book = pictureBookService.getBookDetail(bookId);
            if (book == null) {
                return R.error("绘本不存在");
            }

            Map<String, Object> data = new HashMap<>();
            data.put("book", book);
            return R.ok("获取绘本详情成功").data(data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取绘本详情失败: " + e.getMessage());
        }
    }

    /**
     * 更新阅读进度
     */
    @RequiresPermissions("learning:reading:view")
    @PostMapping("/reading/progress")
    public R updateReadingProgress(@RequestBody Map<String, Object> request) {
        try {
            // 获取当前登录用户
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()) {
                return R.error("用户未登录");
            }

            SysUser currentUser = (SysUser) subject.getPrincipal();
            if (currentUser == null) {
                return R.error("无法获取用户信息");
            }

            Long bookId = Long.valueOf(request.get("bookId").toString());
            Integer currentPage = Integer.valueOf(request.get("currentPage").toString());
            Integer totalPages = Integer.valueOf(request.get("totalPages").toString());

            pictureBookService.updateReadingProgress(currentUser.getId(), bookId, currentPage, totalPages);

            return R.ok("更新阅读进度成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("更新阅读进度失败: " + e.getMessage());
        }
    }

    @RequiresPermissions("learning:reading:view")
    @PostMapping("/reading/start")
    public R startReading(@RequestBody Map<String, Object> request) {
        String bookName = (String) request.get("bookName");
        Map<String, Object> data = new HashMap<>();
        data.put("sessionId", "READ_" + System.currentTimeMillis());
        data.put("book", bookName);
        data.put("status", "reading");
        data.put("progress", 0);

        return R.ok("开始绘本阅读").data(data);
    }

    @GetMapping("/game/levels")
    public R getGameLevels(@RequestParam(required = false, defaultValue = "easy") String difficulty) {
        Map<String, Object> data = new HashMap<>();
        java.util.List<Map<String, Object>> levels = new java.util.ArrayList<>();

        // 根据难度生成关卡
        if ("easy".equals(difficulty)) {
            // 简单模式：20个关卡（6个字母关卡 + 14个常见物关卡）
            // 字母关卡
            levels.add(createLevel(1, "字母A-D", false, 0));
            levels.add(createLevel(2, "字母E-H", false, 0));
            levels.add(createLevel(3, "字母I-L", false, 0));
            levels.add(createLevel(4, "字母M-P", false, 0));
            levels.add(createLevel(5, "字母Q-T", false, 0));
            levels.add(createLevel(6, "字母U-X", false, 0));
            // 常见物关卡
            String[] easyNames = {"水果乐园", "日常用品", "动物朋友", "交通工具", "身体部位",
                    "颜色世界", "数字王国", "食物天地", "学校用品", "家庭成员",
                    "自然景观", "天气变化", "动作词汇", "综合练习"};
            for (int i = 0; i < easyNames.length; i++) {
                levels.add(createLevel(7 + i, easyNames[i], false, 0));
            }
        } else if ("medium".equals(difficulty)) {
            // 中等模式：25个关卡（小学生必掌握单词）
            String[] mediumNames = {"基础单词1", "基础单词2", "基础单词3", "动物世界", "动物朋友",
                    "颜色认知", "多彩世界", "数字学习", "数字应用", "身体部位",
                    "身体认知", "家庭成员", "家庭关系", "学校用品", "校园生活",
                    "食物单词", "美味食物", "动作单词", "日常动作", "时间表达",
                    "星期月份", "天气词汇", "季节变化", "形状认知", "综合测试"};
            for (int i = 1; i <= 25; i++) {
                levels.add(createLevel(i, mediumNames[i - 1], false, 0));
            }
        } else if ("hard".equals(difficulty)) {
            // 困难模式：30个关卡（初中生必掌握单词）
            String[] hardNames = {"初中基础1", "初中基础2", "初中基础3", "学科词汇", "数学词汇",
                    "科学词汇", "情感表达", "情绪词汇", "时间表达", "时间管理",
                    "天气词汇", "气候环境", "运动项目", "体育运动", "交通工具",
                    "出行方式", "职业词汇", "工作职业", "形容词1", "形容词2",
                    "动词短语1", "动词短语2", "名词词汇", "副词应用", "介词用法",
                    "连词连接", "日常对话", "情景交际", "阅读理解", "综合测试"};
            for (int i = 1; i <= 30; i++) {
                levels.add(createLevel(i, hardNames[i - 1], false, 0));
            }
        } else {
            // 默认简单模式
            levels.add(createLevel(1, "字母A-D", false, 0));
            levels.add(createLevel(2, "字母E-H", false, 0));
        }

        data.put("levels", levels);
        return R.ok("获取游戏关卡成功").data(data);
    }

    private Map<String, Object> createLevel(int level, String name, boolean completed, int stars) {
        Map<String, Object> levelMap = new HashMap<>();
        levelMap.put("level", level);
        levelMap.put("name", name);
        levelMap.put("completed", completed);
        levelMap.put("stars", stars);
        return levelMap;
    }

    /**
     * 获取排行榜（允许匿名访问）
     * @param classId 班级ID，如果为null且用户已登录，则自动获取当前用户的班级ID；如果为null且用户未登录，则返回全部排名
     * @return 排行榜数据
     */
    @GetMapping("/leaderboard")
    public R getLeaderboard(@RequestParam(required = false) Long classId) {
        try {
            // 如果classId为null，尝试从当前登录用户获取班级ID
            if (classId == null) {
                try {
                    Subject subject = SecurityUtils.getSubject();
                    System.out.println("排行榜接口 - Subject认证状态: " + subject.isAuthenticated());
                    if (subject.isAuthenticated()) {
                        SysUser currentUser = (SysUser) subject.getPrincipal();
                        System.out.println("排行榜接口 - 当前用户: " + (currentUser != null ? currentUser.getUsername() : "null"));
                        if (currentUser != null && "02".equals(currentUser.getUserType())) {
                            // 当前用户是学生，获取其班级ID
                            List<SysStudentClass> currentStudentClasses = sysStudentClassMapper.findByStudentId(currentUser.getId());
                            if (currentStudentClasses != null && !currentStudentClasses.isEmpty()) {
                                SysStudentClass currentStudentClass = currentStudentClasses.get(0);
                                classId = currentStudentClass.getClassId();
                                System.out.println("排行榜接口 - 自动获取班级ID: " + classId);
                            } else {
                                System.out.println("排行榜接口 - 学生未分配班级");
                            }
                        } else {
                            System.out.println("排行榜接口 - 当前用户不是学生或用户为空");
                        }
                    } else {
                        System.out.println("排行榜接口 - 用户未登录");
                    }
                } catch (Exception e) {
                    // 如果获取当前用户失败，继续使用null（返回全部排名）
                    System.out.println("获取当前用户班级ID失败: " + e.getMessage());
                    e.printStackTrace();
                }
            } else {
                System.out.println("排行榜接口 - 使用前端传递的班级ID: " + classId);
            }

            // 获取所有学生（user_type='02'）
            List<SysUser> allUsers = sysUserMapper.findAll();
            List<SysUser> allStudents = new ArrayList<>();
            for (SysUser user : allUsers) {
                if (user != null && "02".equals(user.getUserType())) {
                    allStudents.add(user);
                }
            }

            List<Map<String, Object>> ranking = new ArrayList<>();

            for (SysUser student : allStudents) {
                // 获取学生所在班级
                List<SysStudentClass> studentClasses = sysStudentClassMapper.findByStudentId(student.getId());
                String className = "未知班级";
                Long studentClassId = null;

                if (studentClasses != null && !studentClasses.isEmpty()) {
                    SysStudentClass studentClass = studentClasses.get(0);
                    studentClassId = studentClass.getClassId();
                    SysClass classInfo = sysClassMapper.findById(studentClassId);
                    if (classInfo != null) {
                        className = classInfo.getClassName();
                    }
                }

                // 如果指定了班级ID，只返回该班级的学生
                if (classId != null && !classId.equals(studentClassId)) {
                    continue;
                }

                // 创建学生排名数据
                Map<String, Object> studentData = new HashMap<>();
                studentData.put("id", student.getId());
                studentData.put("name", student.getNickname() != null ? student.getNickname() : student.getUsername());
                studentData.put("username", student.getUsername());
                studentData.put("className", className);
                studentData.put("classId", studentClassId);
                studentData.put("totalStars", 0); // 默认积分为0，前端会根据localStorage更新

                ranking.add(studentData);
            }

            // 按ID排序（保持一致性），前端会根据积分重新排序
            ranking.sort((a, b) -> {
                Long idA = (Long) a.get("id");
                Long idB = (Long) b.get("id");
                return idA.compareTo(idB);
            });

            Map<String, Object> data = new HashMap<>();
            data.put("ranking", ranking);
            return R.ok("获取排行榜成功").data(data);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取排行榜失败: " + e.getMessage());
        }
    }
}